const path = require('path')
const fs = require('fs')
const md5 = require('md5')
const {
    promisify
} = require('util');

// 导入模型
const query = require('../model/query.js')

const UserController = {};
const {
    password_secret
} = require('../config/config.js')

const rename = promisify(fs.rename)

UserController.userLogin = async (req, res) => {
    //1. 接受参数
    let {
        username,
        password
    } = req.body;
    
    //2. 拼接sql语句，查询用户名和密码是否匹配
    password = md5(`${password}${password_secret}`)
    console.log(password);
    const sql = `select * from users where username = '${username}' and password = '${password}'`
    //3. 成功，
    const result = await query(sql)
    if (result.length > 0) {
        // 将信息记录到session或cookie
        req.session.userInfo = result[0];
        res.cookie('userInfo', JSON.stringify(result[0]), {
            expires: new Date(Date.now() + 1 * 3600000),
        })
        res.json({
            code: 0,
            message: "login success"
        })
    } else {
        // 失败则提示用户
        res.json({
            code: -2,
            message: "login fail"
        })
    }

}

UserController.userLogout = async (req, res) => {
    //1. 清除session
    req.session.destroy(function (err) {
        if (err) {
            throw err;
        }
    })
    //2. 响应json
    res.json({
        code: 0,
        message: "logout success"
    })

}

UserController.updUserInfo = async (req, res) => {
    const {
        id,
        intro
    } = req.body;
    const sql = `update users set intro = '${intro}' where id = ${id}`;
    const {
        affectedRows
    } = await query(sql)
    const successData = {
        code: 0,
        message: "update user success"
    }
    const failData = {
        code: -5,
        message: "update user fail"
    }

    if (affectedRows > 0) {
        // 取出用户信息，再同步session和cookie中的用户信息
        const sql = `select * from users where id = ${id}`
        const result = await query(sql)
        // 将信息记录到session或cookie
        req.session.userInfo = result[0];
        res.cookie('userInfo', JSON.stringify(result[0]), {
            expires: new Date(Date.now() + 1 * 3600000),
        })

        res.json(successData)
    } else {
        res.json(failData)
    }
}

UserController.avatar = async (req, res) => {
    // 1. 获取用户在session中的信息
    const {
        id
    } = req.session.userInfo;
    // 2. 负责文件上传
    let pic = ''
    if (req.file) {
        // 2. 上传文件得到路径
        let {
            destination,
            originalname,
            filename
        } = req.file;
        let extName = originalname.substring(originalname.lastIndexOf('.'))
        let uploadDir = './uploads'
        let oldName = path.join(uploadDir, filename);
        let newName = path.join(uploadDir, filename) + extName;

        try {
            const result = await rename(oldName, newName)
            pic = `uploads/${filename}${extName}`
            // 删除原图，必须得到旧图路径(从session获取)
            // uploads/c47d435adddc1193589e5e93e26e6395.jpg
            let oldAvatar = req.session.userInfo.avatar;
            oldAvatar = path.join(path.dirname(__dirname), oldAvatar)
            fs.unlink(oldAvatar, (err) => {})

        } catch (err) {
            console.log('上传失败')
        }

        // 上传成功，把路径写到sql语句中，更新到数据库中
        const sql = `update users set avatar = '${pic}' where id = ${id}`
        await query(sql)
        // 取出用户信息，再同步session和cookie中的用户信息
        const sql2 = `select * from users where id = ${id}`
        const result = await query(sql2)
        // 将信息记录到session或cookie
        req.session.userInfo = result[0];
        res.cookie('userInfo', JSON.stringify(result[0]), {
            expires: new Date(Date.now() + 1 * 3600000),
        })
        res.json({
            code: 0,
            message: "upload success"
        })
    } else {
        res.json({
            code: -6,
            message: "upload fail",

        })
    }
}

UserController.updatePassword = async (req, res) => {
    const {
        oldpwd,
        newpwd,
        renewpwd
    } = req.body;
    const {
        id
    } = req.session.userInfo
    console.log(id); //用户的ID = 5
    // 第一、对前台传递过来的旧密码进行加密处理，去数据库中的用户加密旧密码进行匹配，是否一致
    let oldPassword = md5(`${oldpwd}${password_secret}`)
    // 第二、去数据库中的用户表中查寻到用户的密码是否与前台传递过来的旧密码是否一致和查询是否是当前用户在进行修改密码操作也就是说用户的id
    const sql = `select * from users where password = '${oldPassword}' and id = '${id}'` // and 就是并且的意思
    query(sql).then(result => {
        // 你这里应该做的是什么?查询到了有数据对吧
        if (result.length) {
            // 那么,有数据之后就去判断一下他的密码是否与我上面加密的旧密码是否一致，而不是没有加密的那个旧密码
            // oldpwd 是没有加密的,而你数据库里却是一个加密的密码,懂? 所以应该是加密对加密的密码,而不是有加密的密码去匹配不加密的密码
            // 然后呢,对于匹配原密码不一致的话直接返回原密码输入错误,对于原密码正确的进行修改成新密码 
            if (result[0].password !== oldPassword) {
                res.json({
                    code: -1,
                    message: "原密码输入错误"
                })
            } else {
                //这里 就是把新密码更新到数据库中
                let newPassword = md5(`${newpwd}${password_secret}`)
                let sql = `update users set password  = "${newPassword}" where id = ${id}`
                return query(sql);
            }
        }
    }).then(result => {
        if (result.affectedRows) {
            res.json({
                code: 20000,
                message: '更新密码成功'
            })
        } else {
            res.json({
                code: -2,
                message: '服务器繁忙，请稍后再试'
            })
        }
    })


}



module.exports = UserController;